"""
@File    : UiBaseClass.py
@Time    : 2019/8/2 9:46
@Author  : LiuFeiYu
@Email   : liufeiyu@sunrise.net
@Software: PyCharm
"""
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from time import sleep


def open_browser(browser='chrome'):
    driver = None
    if browser == 'chrome':
        driver = webdriver.Chrome()
    elif browser == 'firefox':
        driver = webdriver.Firefox()
    elif browser == 'ie':
        driver = webdriver.Ie()
    else:
        print('请使用正确的浏览器打开 [Chrome  firefox  ie]')
    driver.maximize_window()
    return driver


class Base:
    def __init__(self, driver):
        self.driver = driver

    def open_url(self, url):
        """打开网址"""
        self.driver.get(url)

    @staticmethod
    def time_sleep(time=5):
        """时间休眠"""
        sleep(time)

    def back(self):
        """后退"""
        self.driver.back()

    def refresh(self):
        """刷新"""
        self.driver.refresh()

    def implicitly_wait(self, time=10):
        self.driver.implicitly_wait(time)

    def get_attribute(self, loctor, attribute):
        self.find_element(loctor).get_attribute(attribute)

    def get_tag_text(self, loctor):
        try:
            text = self.find_element(loctor).text
            return text
        except:
            print('标签没有text值')

    def find_element(self, locator, timeout=10):
        """
        定位单个元素，如果定位到元素则返回元素，否则返回False
        :param locator: 元祖（by.XXX,value）
        :param timeout: 秒数
        :return:
        """
        try:
            ele = WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(locator))
        except:
            print(f'元素未找到 -> {locator}')
            return False
        else:
            return ele

    def find_elements(self, locator, timeout=10):
        """
        定位一组元素，如果定位到元素则返回元素(list)，否则返回False
        :param locator: 元祖（by.XXX,value）
        :param timeout: 秒数
        :return:
        """
        try:
            eles = WebDriverWait(self.driver, timeout).until(EC.presence_of_all_elements_located(locator))
        except:
            print(f'元素未找到 -> {locator}')
            return False
        else:
            return eles

    def seletor_by_index(self, locator, index):
        """下拉框通过index选择元素"""
        seletor = Select(self.find_element(locator))
        try:
            seletor.select_by_index(index)
        except:
            print('下拉框元素未找到')

    def seletor_by_value(self, locator, value):
        """下拉框通过value选择元素"""
        seletor = Select(self.find_element(locator))
        try:
            seletor.select_by_value(value)
        except:
            pass

    def scroll(self, to):
        """下拉滚动条"""
        try:
            js = f'window.scrollTo(0, {to})'
            self.driver.execute_script(js)
        except:
            print('下拉滚动条失败')

    def click(self, locator, timeout=10):
        """点击元素"""
        ele = self.find_element(locator, timeout)
        try:
            ele.click()
        except:
            pass

    def click_elements(self, locator, timeout=10):
        """分别点击一组元素"""
        eles = self.find_elements(locator, timeout)
        eles = [i for i in eles]
        for x in eles:
            x.click()
            sleep(2)
            self.back()
            self.refresh()
            sleep(2)

    def click_one_checkbox(self, locator, timeout=10):
        """点击单个checkbox"""
        try:
            ele = self.find_element(locator, timeout)
            res = ele.is_selected()
            if res:
                pass
            else:
                ele.click()
        except Exception as e:
            return e

    def send_keys(self, locator, text, timeout=10):
        ele = self.find_element(locator, timeout)
        try:
            ele.clear()
            ele.send_keys(text)
        except:
            pass

    def check_text_in_element(self, locator, text, timeout=10):
        """
        判断text本文是否为一致
        :param locator:元祖
        :param text:需要检查的文本信息
        :param timeout:描述
        :return:
        """
        try:
            res = WebDriverWait(self.driver, timeout).until \
                (EC.text_to_be_present_in_element(locator, text))
        except:
            print(f'元素没有找到 -> {locator}')
            return False
        else:
            return res

    def check_value_in_element(self, locator, text, timeout=10):
        """检查元素属性value值和传入text是否一致"""
        try:
            res = WebDriverWait(self.driver, timeout).until \
                (EC.text_to_be_present_in_element_value(locator, text))
        except:
            print(f'元素没有找到 -> {locator}')
            return False
        else:
            return res

    def to_frame(self, id_or_name):
        """通过id和name属性进入frame"""
        try:
            self.driver.switch_to.frame(id_or_name)
        except:
            print(f'元素未找到 -> {id_or_name}')

    def to_frame_by_other_attribute(self, locator):
        """通过定位frame标签的方式进入frame"""
        try:
            self.driver.switch_to.frame(self.find_element(locator, timeout=10))
        except:
            """
            因为调用find_element方法,已经对未找到元素进行异常捕获
            所以在这里如果switch_to.frame发生异常则不显示,避免重复捕获异常
            """
            pass

    def exit_to_seed_frame(self):
        """返回上级frame"""
        self.driver.switch_to.parent_frame()

    def exit_to_default_frame(self):
        """放回最外层frame"""
        self.driver.switch_to.default_content()

    def close_present_browser(self):
        """关闭当前窗口,不关闭浏览器驱动"""
        self.driver.close()

    def close_browser(self):
        """关闭所有窗口,并关闭浏览器驱动"""
        self.driver.quit()
